package com.ruoyi.web.service.impl;

import com.aliyuncs.live.model.v20161101.DescribeLiveStreamStateRequest;
import com.aliyuncs.live.model.v20161101.DescribeLiveStreamStateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.RoleCameraMapper;
import com.ruoyi.web.domain.MonitorArea;
import com.ruoyi.web.domain.MonitorCamera;
import com.ruoyi.web.domain.dto.MonitorAreaDto;
import com.ruoyi.web.domain.dto.MonitorCameraDto;
import com.ruoyi.web.domain.vo.MonitorCameraVo;
import com.ruoyi.web.mapper.MonitorAreaMapper;
import com.ruoyi.web.mapper.MonitorCameraMapper;
import com.ruoyi.web.service.IMonitorCameraService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class MonitorCameraServiceImpl extends ServiceImpl<MonitorCameraMapper, MonitorCamera> implements IMonitorCameraService {

    @Autowired
    private MonitorCameraMapper monitorCameraMapper;
    @Autowired
    private AliyunLiveService aliyunLiveService;
    @Autowired
    private MonitorAreaMapper monitorAreaMapper;
    @Autowired
    private RoleCameraMapper roleCameraMapper;

    @Override
    public AjaxResult add(MonitorAreaDto dto) {
        int code = getCameraStatus(dto);
        if (code == -1){
            return AjaxResult.error("添加的摄像头获取阿里云状态失败，请检查配置");
        }
//        MonitorCamera monitorCamera = new MonitorCamera();
//        BeanUtils.copyProperties(dto, monitorCamera);
//        monitorCamera.setCreator(SecurityUtils.getUserId());
//        monitorCamera.setCreateTime(LocalDateTime.now());
//        monitorCamera.setUpdateTime(LocalDateTime.now());
//        monitorCameraMapper.insert(monitorCamera);
//        return AjaxResult.success("新增成功");

        // 校验当前区域下是否已存在该名称的子区域
        MonitorArea repetitiveArea = monitorAreaMapper.selectOne(new LambdaQueryWrapper<MonitorArea>().eq(MonitorArea::getBaseParentId, dto.getBaseParentId()).eq(MonitorArea::getBaseName, dto.getBaseName()));
        if (repetitiveArea != null) {
            return AjaxResult.error("当前区域下已存在该名称的子区域");
        }
        MonitorArea monitorArea = new MonitorArea();
        BeanUtils.copyProperties(dto, monitorArea);
        List<MonitorArea> monitorAreas = monitorAreaMapper.selectList(new LambdaQueryWrapper<MonitorArea>().eq(MonitorArea::getBaseParentId, dto.getBaseParentId()).orderByDesc(MonitorArea::getSort));
        if (monitorAreas.isEmpty()) {
            monitorArea.setSort(0);
            MonitorArea parentMonitorArea = monitorAreaMapper.selectById(dto.getBaseParentId());
            monitorArea.setAncestors(parentMonitorArea.getAncestors() + "," + parentMonitorArea.getBaseId());
        } else {
            monitorArea.setSort(monitorAreas.get(0).getSort() + 1);
            monitorArea.setAncestors(monitorAreas.get(0).getAncestors());
        }
        monitorArea.setType("2");
        monitorArea.setCreator(SecurityUtils.getUserId());
        monitorArea.setCreateTime(LocalDateTime.now());
        monitorArea.setUpdateTime(LocalDateTime.now());
        monitorAreaMapper.insert(monitorArea);
        return AjaxResult.success("新增成功");
    }

    public int getCameraStatus(MonitorAreaDto dto) {
        String domain = dto.getDomain();
        String appName = dto.getAppName();
        String streamName = dto.getStreamName();
        DescribeLiveStreamStateRequest request = new DescribeLiveStreamStateRequest();
        request.setDomainName(domain);
        request.setAppName(appName);
        request.setStreamName(streamName);
        DescribeLiveStreamStateResponse response = aliyunLiveService.describeLiveStreamState(request);
        if(response == null){
            return -1;
        }else{
            dto.setCameraStatus(response.getStreamState());
            return 0;
        }

    }

    @Override
    public List<MonitorCameraVo> getList(MonitorCameraDto dto) {
        return monitorCameraMapper.selectMonitorCameraList(dto);
    }

    @Override
    public MonitorCameraVo getDetails(Long baseId) {
        return monitorCameraMapper.selectDetails(baseId);
    }

    @Override
    public AjaxResult update(MonitorAreaDto dto) {
        int code = getCameraStatus(dto);
        if (code == -1){
            return AjaxResult.error("添加的摄像头获取阿里云状态失败，请检查配置");
        }
//        MonitorCamera monitorCamera = new MonitorCamera();
//        BeanUtils.copyProperties(dto, monitorCamera);
//        monitorCamera.setModifier(SecurityUtils.getUserId());
//        monitorCamera.setUpdateTime(LocalDateTime.now());
//        monitorCameraMapper.updateById(monitorCamera);
//        return AjaxResult.success("编辑成功");

        MonitorArea area = monitorAreaMapper.selectById(dto.getBaseId());
        if (! StringUtils.equals(dto.getBaseName(), area.getBaseName())) {
            // 校验当前区域下是否已存在该名称的子区域
            MonitorArea repetitiveArea = monitorAreaMapper.selectOne(new LambdaQueryWrapper<MonitorArea>().eq(MonitorArea::getBaseParentId, dto.getBaseParentId()).eq(MonitorArea::getBaseName, dto.getBaseName()));
            if (repetitiveArea != null) {
                return AjaxResult.error("当前区域下已存在该名称的子区域");
            }
        }
        MonitorArea monitorArea = new MonitorArea();
        BeanUtils.copyProperties(dto, monitorArea);
        monitorArea.setModifier(SecurityUtils.getUserId());
        monitorArea.setUpdateTime(LocalDateTime.now());
        monitorAreaMapper.updateById(monitorArea);
        return AjaxResult.success("编辑成功");
    }

    @Override
    public AjaxResult delete(MonitorAreaDto dto) {
        // 查询当前区域是否绑定角色
        Integer roleCameraCount = roleCameraMapper.selectCountByCameraId(dto.getBaseId());
        if(roleCameraCount > 0) {
            return AjaxResult.error("当前摄像头访问权限已经授予"+roleCameraCount+"个系统角色，请先解除授权");
        }
        monitorAreaMapper.update(new LambdaUpdateWrapper<MonitorArea>().eq(MonitorArea::getBaseId, dto.getBaseId()).set(MonitorArea::getModifier, SecurityUtils.getUserId()).set(MonitorArea::getUpdateTime, LocalDateTime.now()).set(MonitorArea::getIsDelete, 1));
        return AjaxResult.success("删除成功");
    }
}
